package customize

import (
	"encoding/base64"
	"encoding/json"
	"fmt"

	"gitcode.com/G-YT/baoyou/server/global"
	"gitcode.com/G-YT/baoyou/server/model/common/request"
	"gitcode.com/G-YT/baoyou/server/model/common/response"
	"gitcode.com/G-YT/baoyou/server/model/customize"
	customizeReq "gitcode.com/G-YT/baoyou/server/model/customize/request"
	customizeRes "gitcode.com/G-YT/baoyou/server/model/customize/response"
	"gitcode.com/G-YT/baoyou/server/service"
	"gitcode.com/G-YT/baoyou/server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type ConstitutionApi struct {
}

var constitutionService = service.ServiceGroupApp.CustomizeServiceGroup.ConstitutionService

// GetConstitutionQuestion 获取体质问卷
// @Tags Constitution
// @Summary 获取体质辨别页面
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query user.User true "获取体质辨别页面"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /api/assess/getPhysiqueDiscernPage [get]
func (constitutionApi *ConstitutionApi) GetConstitutionQuestion(c *gin.Context) {
	var ItemInfo []customize.Item
	qConf, _ := ConstitutionService.QuestionConf()
	for key, value := range qConf {
		item := customize.Item{
			Key: base64.StdEncoding.EncodeToString([]byte(key)),
			Msg: value,
		}
		ItemInfo = append(ItemInfo, item)
	}
	response.Result(200, ItemInfo, "获取成功!", c)
}

// SubmitConstitutionQuestion 提交体质问卷
// @Tags Constitution
// @Summary 用id查询用户
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query user.User true "提交体质问卷"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"提交成功"}"
// @Router /api/assess/submitPhysiqueQuestion [post]
func (constitutionApi *ConstitutionApi) SubmitConstitutionQuestion(c *gin.Context) {
	var question customize.ConstitutionQuestionLog
	e := c.ShouldBindJSON(&question)
	if e != nil {
		response.FailWithMessage(e.Error(), c)
		return
	}
	id := utils.GetUserID(c)
	var results map[string]int
	if err := json.Unmarshal([]byte(question.Results), &results); err != nil {
		response.FailWithMessage("无效的问卷答案结果集", c)
		return
	}
	// 计算分值及体质
	UserPhysique, _ := ConstitutionService.GetConstitutionInfo(results, question.Birthday)
	LowTension := question.LowTension
	if question.LowTension == ",,,," {
		LowTension = "0,0,0,0,0"
	} else {
		LowTension = question.LowTension
	}
	HighTension := question.HighTension
	if question.HighTension == ",,,," {
		HighTension = "0,0,0,0,0"
	} else {
		HighTension = question.HighTension
	}
	// 拿到体质ID
	Pid, _ := ConstitutionService.GetConstitutionID(UserPhysique.Constitution)
	questionData := &customize.ConstitutionQuestionLog{
		BloodType:          question.BloodType,
		BloodSugar:         question.BloodSugar,
		HRV:                question.HRV,
		BloodConcentration: question.BloodConcentration,
		HRres:              question.HRres,
		LowTension:         LowTension,
		HighTension:        HighTension,
		Birthday:           question.Birthday,
		Results:            question.Results,
		ScoreData:          UserPhysique.Score,
		Physique:           UserPhysique.Constitution,
		PhysiqueId:         Pid.ID,
		Uid:                id,
		Remark:             "",
		Mah:                question.Mah,
		Sh:                 question.Sh,
		Hs:                 question.Hs,
		Pacemaker:          question.Pacemaker,
		Other:              question.Other,
	}
	if logID, err := ConstitutionService.CreateConstitutionQuestionLog(questionData); err != nil {
		global.GVA_LOG.Error("提交失败!", zap.Error(err))
		response.FailWithMessage("提交失败", c)
	} else {
		response.Result(200, logID, "提交成功", c)
	}
}

// GetConstitutionResult 获取问卷结果
// @Tags Constitution
// @Summary 获取问卷结果
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query user.User true "获取问卷结果"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /api/assess/getQuestionResult [get]
func (constitutionApi *ConstitutionApi) GetConstitutionResult(c *gin.Context) {
	id := utils.GetUserID(c)
	UserPhysique, _ := ConstitutionService.GetConstitutionQuestionLog(map[string]interface{}{"uid": id}, "id,created_at,score_data,habitus,remark")
	data := make(map[string]int)
	err := json.Unmarshal([]byte(UserPhysique.ScoreData), &data)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	var result customizeRes.Data
	for k, v := range data {
		decoded, _ := base64.StdEncoding.DecodeString(k)
		result.Title = append(result.Title, string(decoded))
		result.Score = append(result.Score, v)
	}
	if UserPhysique.ID == 0 {
		response.FailWithMessage("您还没有进行过体质评测!", c)
		return
	} else {
		response.Result(200,
			customizeRes.ConstitutionResultResponse{
				ID:        UserPhysique.ID,
				Habitus:   UserPhysique.Physique + "质",
				CreatedAt: UserPhysique.CreatedAt,
				Data: customizeRes.Data{
					Title:  result.Title,
					Score:  result.Score,
					Remark: UserPhysique.Remark,
				},
			}, "获取成功", c)
	}
}

// GetConstitutionResultList 获取问卷结果列表
// @Tags Constitution
// @Summary 获取问卷结果列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query user.User true "获取问卷结果列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /api/assess/getQuestionResultList [get]
func (constitutionApi *ConstitutionApi) GetConstitutionResultList(c *gin.Context) {
	id := utils.GetUserID(c)
	UserPhysiqueList, _ := ConstitutionService.GetConstitutionQuestionList(map[string]interface{}{"uid": id}, "id,created_at,physique_id,habitus,score_data")
	results := make([]customizeRes.ConstitutionResultResponse, 0)
	for _, value := range UserPhysiqueList {
		dataMap := make(map[string]int)
		if err := json.Unmarshal([]byte(value.ScoreData), &dataMap); err != nil {
			fmt.Printf("JSON解析失败: %v\n", err)
			continue
		}
		var data customizeRes.Data
		for k, v := range dataMap {
			decoded, _ := base64.StdEncoding.DecodeString(k)
			data.Title = append(data.Title, string(decoded))
			data.Score = append(data.Score, v)
		}
		data.Remark = value.Remark
		results = append(results, customizeRes.ConstitutionResultResponse{
			ID:        value.ID,
			Habitus:   value.Physique + "质",
			CreatedAt: value.CreatedAt,
			Data:      data,
		})
	}
	response.Result(200, results, "获取成功", c)
}

// GetOneConstitutionResultByID 根据ID获取问卷结果
// @Tags Constitution
// @Summary 根据ID获取问卷结果
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query user.User true "根据ID获取问卷结果"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"提交成功"}"
// @Router /api/assess/getOneQuestionResultByID [get]
func (constitutionApi *ConstitutionApi) GetOneConstitutionResultByID(c *gin.Context) {
	id := c.Query("id")
	UserPhysique, _ := ConstitutionService.GetConstitutionQuestionLog(map[string]interface{}{"id": id}, "id,created_at,score_data,habitus,remark")
	data := make(map[string]int)
	err := json.Unmarshal([]byte(UserPhysique.ScoreData), &data)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	var result customizeRes.Data
	for k, v := range data {
		decoded, _ := base64.StdEncoding.DecodeString(k)
		result.Title = append(result.Title, string(decoded))
		result.Score = append(result.Score, v)
	}
	if UserPhysique.ID == 0 {
		response.FailWithMessage("您还没有进行过体质评测!", c)
		return
	} else {
		response.Result(200,
			customizeRes.ConstitutionResultResponse{
				ID:        UserPhysique.ID,
				Habitus:   UserPhysique.Physique + "质",
				CreatedAt: UserPhysique.CreatedAt,
				Data: customizeRes.Data{
					Title:  result.Title,
					Score:  result.Score,
					Remark: UserPhysique.Remark,
				},
			}, "获取成功", c)
	}
}

// CreateConstitution 创建体质
// @Tags Constitution
// @Summary 创建体质
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body customize.Constitution true "创建体质"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /constitution/createPhysique [post]
func (constitutionApi *ConstitutionApi) CreateConstitution(c *gin.Context) {
	var constitution customize.Constitution
	err := c.ShouldBindJSON(&constitution)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := constitutionService.CreateConstitution(&constitution); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteConstitution 删除体质
// @Tags Constitution
// @Summary 删除体质
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body customize.Constitution true "删除体质"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /physique/deleteConstitution [delete]
func (constitutionApi *ConstitutionApi) DeleteConstitution(c *gin.Context) {
	var physique customize.Constitution
	err := c.ShouldBindJSON(&physique)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := constitutionService.DeleteConstitution(physique); err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// DeleteConstitutionByIds 批量删除体质
// @Tags Constitution
// @Summary 批量删除体质
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除体质"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /physique/deletePhysiqueByIds [delete]
func (constitutionApi *ConstitutionApi) DeleteConstitutionByIds(c *gin.Context) {
	var IDS request.IdsReq
	err := c.ShouldBindJSON(&IDS)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := constitutionService.DeleteConstitutionByIds(IDS); err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败", c)
	} else {
		response.OkWithMessage("批量删除成功", c)
	}
}

// UpdateConstitution 更新体质
// @Tags Constitution
// @Summary 更新体质
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body customize.Constitution true "更新体质"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /constitution/updateConstitution [put]
func (constitutionApi *ConstitutionApi) UpdateConstitution(c *gin.Context) {
	var physique customize.Constitution
	err := c.ShouldBindJSON(&physique)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := constitutionService.UpdateConstitution(physique); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// FindConstitution 用id查询体质
// @Tags Physique
// @Summary 用id查询体质
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query customize.Constitution true "用id查询体质"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /constitution/findPhysique [get]
func (constitutionApi *ConstitutionApi) FindConstitution(c *gin.Context) {
	var physique customize.Constitution
	err := c.ShouldBindQuery(&physique)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if constitution, err := constitutionService.GetConstitution(physique.ID); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(constitution, c)
	}
}

// GetConstitutionList 分页获取体质列表
// @Tags Constitution
// @Summary 分页获取体质列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query customizeReq.ConstitutionSearch true "分页获取体质列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /physique/getPhysiqueList [get]
func (constitutionApi *ConstitutionApi) GetConstitutionList(c *gin.Context) {
	var pageInfo customizeReq.ConstitutionSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if list, total, err := constitutionService.GetConstitutionInfoList(pageInfo); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.OkWithDetailed(response.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	}
}

func (constitutionApi *ConstitutionApi) SetConstitutionArticle(c *gin.Context) {
	var req customizeReq.ConstitutionArticleReq
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := constitutionService.SetConstitutionArticle(req); err != nil {
		global.GVA_LOG.Error("设置失败!", zap.Error(err))
		response.FailWithMessage("设置失败", c)
	} else {
		response.OkWithMessage("设置成功", c)
	}
}

func (constitutionApi *ConstitutionApi) GetConstitutionArticle(c *gin.Context) {
	constitutionID := c.Query("constitutionID")
	if res, err := constitutionService.GetConstitutionArticle(constitutionID); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.OkWithData(res, c)
	}
}
